package com.bpr.webservice.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.bpr.webservice.domain.Menuaccess;
import com.bpr.webservice.domain.Users;
import com.bpr.webservice.domain.dto.MenuAccessServingDto;
import com.bpr.webservice.repository.UsersRepository;

@Controller
@RequestMapping("/commons")
public class CommonsController {

	@Autowired UsersRepository usersRepository;
	
	@RequestMapping("/menubyloggeduser")
	public List<MenuAccessServingDto> getMenuById(){
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		Users user = usersRepository.authenticate(auth.getName());
		
		List<MenuAccessServingDto> menu = new ArrayList<MenuAccessServingDto>();
		List<MenuAccessServingDto> parent = new ArrayList<MenuAccessServingDto>();
		List<MenuAccessServingDto> child = new ArrayList<MenuAccessServingDto>();
		
		for (Menuaccess m : user.getMenuaccessList()){
			if (m.getMenuid().getVisible() == false){
				continue;
			}
			MenuAccessServingDto all = new MenuAccessServingDto();
			if( m.getLevels() == 0 ){
				all.setMenuid(m.getMenuid().getMenuid());
				all.setName(m.getMenuid().getMenuname());
				all.setLink(m.getMenuid().getLink());
				all.setLevels(m.getLevels());
				all.setParent(m.getParent());
				parent.add(all);
			}else{
				all.setMenuid(m.getMenuid().getMenuid());
				all.setName(m.getMenuid().getMenuname());
				all.setLink(m.getMenuid().getLink());
				all.setLevels(m.getLevels());
				all.setParent(m.getParent());
				child.add(all);				
			}
						
		}
		for (MenuAccessServingDto p : parent) {
			List<MenuAccessServingDto> tmp = new ArrayList<MenuAccessServingDto>();
			for (MenuAccessServingDto c : child) {
				if(c.getParent() == p.getParent()){
					tmp.add(c);	
				}
			}
			p.setChild(tmp);
		}
		menu.addAll(parent);
		return menu;
	}
}
